﻿using d1Common.WebController;
using d1Project.Modules.Common.do4A.Domain;
using d1Project.Modules.Common.do4A.Models;
using d1Project.Tools;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace d1Project.Modules.Common.do4A.Controllers.a2
{
    /// <summary>
    /// 忘记密码
    /// </summary>
    [Route("do4A/a2/User2Pwd")]
    public class User2Pwd2Controller : ControllerBase
    {
        protected override DbContext dbContext
        {
            get { return this.db; }
        }

        private do4ADbContext db = new do4ADbContext();

        public async Task<IHttpActionResult> Put(User2PwdVm model)
        {
            if (!ModelState.IsValid) this.Error("请求参数不正确");

            if (AuthenticationMgr.Instance.Token2_useVerficationCode)
            {
                VerificationCodeMgr.Instance.checkVerificationCode(this.db, model.VerificationId, model.VerificationCode, AuthenticationMgr.Instance.Token2_VerficationMaxErrorCount);
            }

            var entity = await db.User2s.Where(x => x.MobilePhone == model.MobilePhone).FirstOrDefaultAsync();
            if (entity == null) this.Error("此用户不存在");
            var entityPwd = await db.User2Pwds.FindAsync(entity.Id);
            if (entityPwd == null)
            {
                User2Pwd user2Pwd = new User2Pwd();
                user2Pwd.Id = entity.Id;
                user2Pwd.Password = model.Password;
                db.User2Pwds.Add(user2Pwd);
            }
            else
            {
                entityPwd.Password = model.Password;
            }
            await db.SaveChangesAsync();
            return Ok();
        }
    }

    public class User2PwdVm
    {
        /// <summary>
        /// 手机号
        /// </summary>
        [Required]
        public string MobilePhone { get; set; }

        /// <summary>
        /// 密码
        /// </summary>
        [Required]
        public string Password { get; set; }

        /// <summary>
        /// 验证码Id
        /// </summary>
        public string VerificationId { get; set; }

        /// <summary>
        /// 验证码值
        /// </summary>
        public string VerificationCode { get; set; }

    }
}
